package routers

import (
	"github.com/beego/beego/v2/server/web/context"

	"gitee.com/yizhongi/wfw/controllers"
	"github.com/beego/beego/v2/server/web"
)

// FilterUser 是登录验证拦截器
var FilterUser = func(ctx *context.Context) {
	userName := ctx.Input.Session("uid")
	url := ctx.Request.URL.Path
	list := []string{"/login", "/logout", "/register", "/favicon.ico"}
	if userName == nil && !in(url, list) {
		ctx.Redirect(302, "/login")
	}
}

func in(target string, strArray []string) bool {
	for _, element := range strArray {
		if target == element {
			return true
		}
	}
	return false
}

func init() {
	// 验证用户是否已经登录
	web.InsertFilter("/*", web.BeforeRouter, FilterUser)

	web.Router("/", &controllers.MainController{})

	web.Include(&controllers.UserRegisterController{})

	web.Include(&controllers.UserLoginController{})

	web.Include(&controllers.UserLogoutController{})

	web.Include(&controllers.WelcomeController{})

	web.Include(&controllers.TaskController{})

	web.Include(&controllers.StoreController{})

	web.Include(&controllers.WebhookController{})

	web.Include(&controllers.TaskRunController{})

	ns := web.NewNamespace("/api",
		web.NSNamespace("/task", web.NSInclude(&controllers.TaskApiController{})),
		web.NSNamespace("/store", web.NSInclude(&controllers.StoreApiController{})),
		web.NSNamespace("/container", web.NSInclude(&controllers.ContainerApiController{})),
		web.NSNamespace("/taskrun", web.NSInclude(&controllers.TaskRunApiController{})),
	)
	web.AddNamespace(ns)
}
